package com.ty.config;

import com.ty.utils.AuthorizationInterceptor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.annotation.Resource;

/**
 * Created by IntelliJ IDEA.
 *
 * @author : txy
 * @create : 2024/1/2 20:07
 */
@Configuration
public class Config implements WebMvcConfigurer {
    @Resource
    private AuthorizationInterceptor authorizationInterceptor;
    @Value("${coverPath}")
    private String cover;

    //跨域问题
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        /*
         * 一小时内不需要再预检
         */
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowCredentials(true)
                .allowedHeaders(CorsConfiguration.ALL)
                .allowedMethods(CorsConfiguration.ALL)
                .maxAge(3600);
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //注册拦截器
        registry.addInterceptor(authorizationInterceptor)
                //拦截所有请求
                .addPathPatterns("/**")
                //排除登录方法和匿名方法
                .excludePathPatterns(
                        "/user/createCode",
                        "/user/register",
                        "/user/login",
                        "/book/getBooks",
                        "/book/getBooksByTypeAndName",
                        "/book/getBooksGroupByType",
                        "/book/getBookById",
                        "/bookType/getBookType",
                        "/img/**"
                        //"/**/**.jpeg",
                        //"/**/**.png"
                );
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/img/**")
                .addResourceLocations(cover);
    }
}